<template>
  <div class="page-container">
    <a-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <a-row :gutter="16">
          <a-col :span="5">
            <a-input
              v-model:value="searchParams.nickName"
              placeholder="请输入用户昵称"
              @input="handleSearch"
              allowClear
            >
              <template #prefix>
                <UserOutlined />
              </template>
            </a-input>
          </a-col>
          <a-col :span="5">
            <a-input
              v-model:value="searchParams.phone"
              placeholder="请输入手机号"
              @input="handleSearch"
              allowClear
            >
              <template #prefix>
                <PhoneOutlined />
              </template>
            </a-input>
          </a-col>
          <a-col :span="5">
            <a-input
              v-model:value="searchParams.email"
              placeholder="请输入邮箱"
              @input="handleSearch"
              allowClear
            >
              <template #prefix>
                <MailOutlined />
              </template>
            </a-input>
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="searchParams.userType"
              placeholder="用户类型"
              @change="handleSearch"
              allowClear
              style="width: 100%"
            >
              <a-select-option value="wechat">微信用户</a-select-option>
              <a-select-option value="anonymous">匿名用户</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="5">
            <a-select
              v-model:value="searchParams.userStatus"
              placeholder="用户状态"
              @change="handleSearch"
              allowClear
              style="width: 100%"
            >
              <a-select-option value="normal">正常</a-select-option>
              <a-select-option value="banned">封禁</a-select-option>
            </a-select>
          </a-col>
        </a-row>
      </div>

      <!-- 操作按钮区 -->
      <div class="action-bar">
        <a-space>
          <PermissionButton permission="user:add">
            <a-button type="primary" @click="handleAdd">
              <PlusOutlined />
              新增用户
            </a-button>
          </PermissionButton>

          <a-button @click="handleRefresh">
            <ReloadOutlined />
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        :scroll="{ x: 1600 }"
      >
        <!-- 头像列 -->
        <template #avatar="{ record }">
          <a-avatar :src="record.avatar || record.defaultAvatar" :size="40">
            {{ record.nickName?.charAt(0) || record.defaultNickName?.charAt(0) }}
          </a-avatar>
        </template>

        <!-- 用户信息列 -->
        <template #userInfo="{ record }">
          <div>
            <div class="user-name">{{ record.nickName || record.defaultNickName }}</div>
            <div class="user-detail">{{ record.phone || record.email }}</div>
            <div class="user-detail" v-if="record.stellarMeetCode">
              星遇号: {{ record.stellarMeetCode }}
            </div>
          </div>
        </template>

        <!-- 用户类型列 -->
        <template #userType="{ record }">
          <a-tag v-if="record.userType === 'wechat'" color="green">微信用户</a-tag>
          <a-tag v-else-if="record.userType === 'anonymous'" color="orange">匿名用户</a-tag>
          <a-tag v-else color="default">{{ record.userType }}</a-tag>
        </template>

        <!-- 性别列 -->
        <template #sex="{ record }">
          <a-tag v-if="record.sex === 1" color="blue">男</a-tag>
          <a-tag v-else-if="record.sex === 2" color="pink">女</a-tag>
          <a-tag v-else color="default">未知</a-tag>
        </template>

        <!-- 登录统计列 -->
        <template #loginStats="{ record }">
          <div>
            <div class="login-detail" v-if="record.loginCount">
              登录次数: {{ record.loginCount }}
            </div>
            <div class="login-detail" v-if="record.lastLoginTime">
              最后登录: {{ formatDateTime(record.lastLoginTime) }}
            </div>
            <div class="login-detail" v-if="record.lastIp">IP: {{ record.lastIp }}</div>
          </div>
        </template>

        <!-- 用户状态列 -->
        <template #userStatus="{ record }">
          <a-tag v-if="record.userStatus === 'normal'" color="green">正常</a-tag>
          <a-tag v-else-if="record.userStatus === 'banned'" color="red">封禁</a-tag>
          <a-tag v-else color="default">{{ record.userStatus }}</a-tag>
        </template>

        <!-- 创建时间列 -->
        <template #createdTime="{ record }">
          {{ formatDateTime(record.createdTime) }}
        </template>

        <!-- 操作列 -->
        <template #action="{ record }">
          <a-space>
            <PermissionButton permission="user:edit">
              <a-button type="link" size="small" @click="handleEdit(record)"> 编辑 </a-button>
            </PermissionButton>

            <PermissionButton permission="user:ban">
              <a-button
                type="link"
                size="small"
                :class="record.userStatus === 'banned' ? 'text-success' : 'text-warning'"
                @click="handleToggleStatus(record)"
              >
                {{ record.userStatus === 'banned' ? '解封' : '封禁' }}
              </a-button>
            </PermissionButton>

            <PermissionButton permission="user:delete">
              <a-button type="link" size="small" danger @click="handleDelete(record)">
                删除
              </a-button>
            </PermissionButton>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑用户弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalType === 'add' ? '新增用户' : '编辑用户'"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="900px"
      :body-style="{ padding: '24px 24px 16px' }"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        layout="horizontal"
      >
        <!-- 基础信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <UserOutlined class="section-icon" />
            基础信息
          </div>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="用户类型" name="userType">
                <a-select v-model:value="formData.userType" placeholder="请选择用户类型">
                  <a-select-option value="wechat">
                    <div class="user-type-option">
                      <span class="type-icon wechat">微</span>
                      微信用户
                    </div>
                  </a-select-option>
                  <a-select-option value="anonymous">
                    <div class="user-type-option">
                      <span class="type-icon anonymous">匿</span>
                      匿名用户
                    </div>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="用户昵称" name="nickName">
                <a-input
                  v-model:value="formData.nickName"
                  placeholder="请输入用户昵称"
                  :maxlength="20"
                  show-count
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="手机号" name="phone">
                <a-input
                  v-model:value="formData.phone"
                  placeholder="请输入手机号"
                  :maxlength="11"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="邮箱" name="email">
                <a-input v-model:value="formData.email" placeholder="请输入邮箱地址" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="性别" name="sex">
                <a-radio-group v-model:value="formData.sex">
                  <a-radio :value="1">
                    <span class="gender-option male"> 👨 男 </span>
                  </a-radio>
                  <a-radio :value="2">
                    <span class="gender-option female"> 👩 女 </span>
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="用户状态" name="userStatus">
                <a-select v-model:value="formData.userStatus" placeholder="请选择用户状态">
                  <a-select-option value="normal">
                    <a-tag color="green" style="margin-right: 8px">正常</a-tag>
                    正常使用
                  </a-select-option>
                  <a-select-option value="banned">
                    <a-tag color="red" style="margin-right: 8px">封禁</a-tag>
                    禁止使用
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 学历信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <BookOutlined class="section-icon" />
            学历信息
          </div>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="年级" name="grade">
                <a-input
                  v-model:value="formData.grade"
                  placeholder="如：2023级、大三"
                  :maxlength="20"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="学号" name="studentId">
                <a-input
                  v-model:value="formData.studentId"
                  placeholder="请输入学号"
                  :maxlength="30"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 头像设置区域 -->
        <div class="form-section">
          <div class="section-title">
            <CameraOutlined class="section-icon" />
            头像设置
          </div>

          <a-form-item label="用户头像" name="avatar">
            <div class="avatar-upload-container">
              <!-- 头像预览区域 -->
              <div class="avatar-preview">
                <a-avatar :size="80" :src="formData.avatar || previewAvatar">
                  {{ formData.nickName?.charAt(0) || '用' }}
                </a-avatar>
                <div class="avatar-info">
                  <div class="avatar-tips">
                    <div>支持JPG、PNG、GIF、WEBP格式</div>
                    <div>建议尺寸：200x200像素，大小不超过5MB</div>
                  </div>
                </div>
              </div>

              <!-- 上传组件 -->
              <div class="upload-controls">
                <a-upload
                  :before-upload="beforeAvatarUpload"
                  :show-upload-list="false"
                  accept="image/*"
                  class="avatar-uploader"
                >
                  <a-button type="primary" :loading="uploadLoading">
                    <UploadOutlined />
                    {{ uploadLoading ? '上传中...' : '上传头像' }}
                  </a-button>
                </a-upload>

                <a-button
                  v-if="formData.avatar || previewAvatar"
                  @click="handleRemoveAvatar"
                  style="margin-left: 8px"
                >
                  <DeleteOutlined />
                  移除头像
                </a-button>
              </div>

              <!-- 上传进度 -->
              <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
                <a-progress :percent="uploadProgress" size="small" />
              </div>
            </div>
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
  PlusOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  BookOutlined,
  CameraOutlined,
  UploadOutlined,
} from '@ant-design/icons-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { userService } from '../../api/user'
import type { User } from '../../types'
import { debounce } from '../../utils/debounce'
import PermissionButton from '../../components/PermissionButton.vue'
import { uploadFile, validateFile } from '../../utils/upload'

// 用户分页查询参数接口
interface UserPageParams {
  page: number
  pageSize: number
  id?: number
  userType?: string
  nickName?: string
  phone?: string
  email?: string
  userStatus?: string
  schoolId?: number
  grade?: string
  createdTime?: string
  isDeleted?: number
}

// 页面状态
const loading = ref(false)
const userList = ref<User[]>([])
const modalVisible = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const confirmLoading = ref(false)
const formRef = ref<FormInstance>()

// 上传相关状态
const uploadLoading = ref(false)
const uploadProgress = ref(0)
const previewAvatar = ref('')

// 搜索参数
const searchParams = reactive<UserPageParams>({
  page: 1,
  pageSize: 20,
  nickName: '',
  phone: '',
  email: '',
  userType: undefined,
  userStatus: undefined,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表格列配置
const columns: TableColumnsType = [
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 80,
    align: 'center',
    slots: { customRender: 'avatar' },
  },
  {
    title: '用户信息',
    dataIndex: 'userInfo',
    key: 'userInfo',
    width: 200,
    slots: { customRender: 'userInfo' },
  },
  {
    title: '用户类型',
    dataIndex: 'userType',
    key: 'userType',
    width: 100,
    align: 'center',
    slots: { customRender: 'userType' },
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    width: 80,
    align: 'center',
    slots: { customRender: 'sex' },
  },
  {
    title: '登录统计',
    dataIndex: 'loginStats',
    key: 'loginStats',
    width: 200,
    slots: { customRender: 'loginStats' },
  },
  {
    title: '用户状态',
    dataIndex: 'userStatus',
    key: 'userStatus',
    width: 100,
    align: 'center',
    slots: { customRender: 'userStatus' },
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 180,
    slots: { customRender: 'createdTime' },
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
    fixed: 'right',
    slots: { customRender: 'action' },
  },
]

// 表单数据
const formData = reactive<Partial<User>>({
  userType: 'wechat',
  nickName: '',
  phone: '',
  email: '',
  sex: 1,
  grade: '',
  studentId: '',
  userStatus: 'normal',
  avatar: '',
})

// 表单验证规则
const formRules = {
  userType: [{ required: true, message: '请选择用户类型' }],
  nickName: [
    { required: true, message: '请输入用户昵称' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符' },
  ],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }],
  email: [{ type: 'email', message: '请输入正确的邮箱格式' }],
  sex: [{ required: true, message: '请选择性别' }],
  userStatus: [{ required: true, message: '请选择用户状态' }],
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 防抖搜索
const handleSearch = debounce(() => {
  pagination.current = 1
  searchParams.page = 1
  loadUserList()
}, 500)

// 加载用户列表
const loadUserList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams,
      page: pagination.current,
      pageSize: pagination.pageSize,
    }

    const result = await userService.getUserPage(params)
    userList.value = result.result
    pagination.total = result.total
  } catch (error) {
    message.error('加载用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  searchParams.page = pag.current
  searchParams.pageSize = pag.pageSize
  loadUserList()
}

// 刷新列表
const handleRefresh = () => {
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  modalType.value = 'add'
  modalVisible.value = true
  resetFormData()
}

// 编辑用户
const handleEdit = (record: User) => {
  modalType.value = 'edit'
  modalVisible.value = true
  Object.assign(formData, record)
  // 设置头像预览
  previewAvatar.value = record.avatar || ''
}

// 封禁/解封用户
const handleToggleStatus = (record: User) => {
  const action = record.userStatus === 'banned' ? '解封' : '封禁'
  const statusText =
    record.userStatus === 'banned' ? '解封后用户将恢复正常使用' : '封禁后用户将无法正常使用系统'

  Modal.confirm({
    title: `确认${action}用户`,
    content: `确定要${action}用户 "${record.nickName || record.defaultNickName}" 吗？${statusText}`,
    okText: `确认${action}`,
    cancelText: '取消',
    okButtonProps: {
      danger: record.userStatus === 'normal',
    },
    onOk: async () => {
      try {
        await userService.toggleUserStatus(record.id)
        message.success(`${action}用户成功`)
        loadUserList()
      } catch (error) {
        message.error(`${action}用户失败`)
        console.error(error)
      }
    },
  })
}

// 删除用户
const handleDelete = (record: User) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 "${record.nickName || record.defaultNickName}" 吗？此操作不可恢复！`,
    okText: '确认删除',
    cancelText: '取消',
    okButtonProps: { danger: true },
    onOk: async () => {
      try {
        await userService.deleteUser(record.id)
        message.success('删除成功')
        loadUserList()
      } catch (error) {
        message.error('删除失败')
        console.error(error)
      }
    },
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    confirmLoading.value = true

    if (modalType.value === 'add') {
      await userService.createUser(formData)
      message.success('新增用户成功')
    } else {
      await userService.updateUser(formData)
      message.success('更新用户成功')
    }

    modalVisible.value = false
    loadUserList()
  } catch (error) {
    if (error instanceof Error) {
      message.error(`操作失败: ${error.message}`)
    } else {
      message.error('表单验证失败')
    }
    console.error(error)
  } finally {
    confirmLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetFormData()
}

// 头像上传前验证和处理
const beforeAvatarUpload = async (file: File) => {
  // 验证文件
  if (!validateFile(file)) {
    return false
  }

  try {
    uploadLoading.value = true
    uploadProgress.value = 0

    const imageUrl = await uploadFile(file, {
      autoCompress: true,
      quality: 0.8,
      maxWidth: 400,
      maxHeight: 400,
      onProgress: (percent: number) => {
        uploadProgress.value = percent
      },
      onSuccess: (url: string) => {
        formData.avatar = url
        previewAvatar.value = url
        message.success('头像上传成功')
      },
      onError: (error: Error) => {
        console.error('上传失败:', error)
        message.error('头像上传失败，请重试')
      },
    })

    if (!imageUrl) {
      throw new Error('上传失败')
    }

    // 上传成功后设置头像URL
    formData.avatar = imageUrl
    previewAvatar.value = imageUrl
  } catch (error) {
    console.error('上传异常:', error)
    message.error('头像上传失败，请重试')
  } finally {
    uploadLoading.value = false
    uploadProgress.value = 0
  }

  return false // 阻止默认上传
}

// 移除头像
const handleRemoveAvatar = () => {
  formData.avatar = ''
  previewAvatar.value = ''
  message.success('头像已移除')
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    userType: 'wechat',
    nickName: '',
    phone: '',
    email: '',
    sex: 1,
    grade: '',
    studentId: '',
    userStatus: 'normal',
    avatar: '',
  })
  previewAvatar.value = ''
  formRef.value?.clearValidate()
}

// 页面初始化
onMounted(() => {
  loadUserList()
})
</script>

<style scoped lang="scss">
.page-container {
  padding: 24px;

  .search-form {
    margin-bottom: 16px;
  }

  .action-bar {
    margin-bottom: 16px;
  }

  .user-name {
    font-weight: 500;
    color: #262626;
    margin-bottom: 2px;
  }

  .user-detail {
    font-size: 12px;
    color: #8c8c8c;
    line-height: 1.4;
  }

  .student-detail {
    font-size: 12px;
    color: #595959;
    line-height: 1.4;
  }

  .login-detail {
    font-size: 12px;
    color: #595959;
    line-height: 1.4;
  }

  .text-placeholder {
    color: #bfbfbf;
    font-style: italic;
  }

  .text-success {
    color: #52c41a !important;
  }

  .text-warning {
    color: #faad14 !important;
  }
}

// 弹出框样式优化
:deep(.ant-modal) {
  .ant-modal-content {
    border-radius: 12px;
    overflow: hidden;
  }

  .ant-modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-bottom: none;
    padding: 20px 24px;

    .ant-modal-title {
      color: white;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .ant-modal-close {
    color: rgba(255, 255, 255, 0.8);

    &:hover {
      color: white;
    }
  }
}

// 表单区域样式
.form-section {
  margin-bottom: 32px;

  &:last-child {
    margin-bottom: 16px;
  }

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 8px;
    border-bottom: 2px solid #f0f0f0;
    font-size: 16px;
    font-weight: 600;
    color: #262626;

    .section-icon {
      margin-right: 8px;
      font-size: 18px;
      color: #1890ff;
    }
  }
}

// 用户类型选项样式
.user-type-option {
  display: flex;
  align-items: center;

  .type-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
    color: white;
    margin-right: 8px;

    &.wechat {
      background: #07c160;
    }

    &.anonymous {
      background: #faad14;
    }
  }
}

// 性别选项样式
.gender-option {
  display: inline-flex;
  align-items: center;
  font-size: 14px;

  &.male {
    color: #1890ff;
  }

  &.female {
    color: #eb2f96;
  }
}

// 头像上传区域样式
.avatar-upload-container {
  .avatar-preview {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 8px;

    .ant-avatar {
      margin-right: 16px;
      border: 3px solid #e6f7ff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .avatar-info {
      flex: 1;

      .avatar-tips {
        color: #8c8c8c;
        font-size: 13px;
        line-height: 1.6;

        div {
          margin-bottom: 2px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }

  .upload-controls {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .avatar-uploader {
      :deep(.ant-upload) {
        .ant-btn {
          height: 40px;
          border-radius: 6px;
          font-weight: 500;
        }
      }
    }
  }

  .upload-progress {
    margin-top: 8px;
  }
}

// 表单项优化
:deep(.ant-form) {
  .ant-form-item {
    margin-bottom: 20px;

    .ant-form-item-label {
      padding-bottom: 4px;

      > label {
        font-weight: 500;
        color: #262626;

        &::after {
          content: none;
        }
      }
    }
  }

  .ant-input,
  .ant-select-selector {
    border-radius: 6px;
    border: 1px solid #d9d9d9;
    transition: all 0.3s;

    &:hover {
      border-color: #40a9ff;
    }

    &:focus,
    &.ant-select-focused {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }

  .ant-radio-wrapper {
    margin-right: 16px;
  }
}

// 按钮样式优化
:deep(.ant-btn) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s;

  &.ant-btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
  }
}
</style> 